/**
 *
 */
package com.yangtao.prototype.system.role.service.impl;

import com.yangtao.framework.service.BaseService;
import com.yangtao.framework.util.StringHelper;
import com.yangtao.prototype.common.tree.CheckBoxTree;
import com.yangtao.prototype.system.dao.MenuTreeDao;
import com.yangtao.prototype.system.dao.OrganizationDao;
import com.yangtao.prototype.system.dao.RoleDao;
import com.yangtao.prototype.system.domain.FunctionAuthority;
import com.yangtao.prototype.system.domain.MenuTree;
import com.yangtao.prototype.system.domain.Role;
import com.yangtao.prototype.system.role.service.RoleService;
import com.yangtao.prototype.system.role.web.RoleModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;

/**
 * 角色管理类
 *
 * @author 杨涛
 */
@Service
public class RoleServiceImpl extends BaseService implements RoleService {
	@Autowired
	private MenuTreeDao menuTreeDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private OrganizationDao organizeDao;

	/**
	 * 加载所有菜单
	 */
	@Override
	public RoleModel loadMenus(RoleModel model) {
		List<CheckBoxTree> trees = new ArrayList<CheckBoxTree>();
		String roleId = model.getRole().getId();
		List<MenuTree> menus = menuTreeDao.findAllMenus();
		Set<String> set = roleDao.loadAuthorizedMenu(roleId);
		for (MenuTree mt : menus) {
			trees.add(CheckBoxTree.loadFromMenu(mt, set));
		}
		model.setMenu(trees);
		return model;
	}

	/**
	 * 保存角色权限
	 */
	@Override
	public RoleModel updateRole(RoleModel model) {
		Assert.notNull(model.getRoleAuth(), "菜单权限不能为空");
		//VO
		Role roleVo = model.getRole();
		//主键
		String roleId = roleVo.getId();
		//PO
		Role rolePo = roleDao.load(roleId);
		//复制属性
		mapper.map(roleVo, rolePo);
		//1 删除已有的权限
		roleDao.deleteAuthorityByRole(roleId);
		//2 增加新的功能权限
		String[] menus = model.getRoleAuth().split(",");
		Set<String> auths = new HashSet<String>();
		List<FunctionAuthority> functionAuthorities = new ArrayList<FunctionAuthority>();
		//通过hashSet，去掉，菜单ID中重复的值
		for (String menu : menus) {
			if (StringUtils.isNotEmpty(menu))
				auths.add(menu);
		}
		//保存新的菜单关联
		for (Iterator<String> it = auths.iterator(); it.hasNext(); ) {
			FunctionAuthority functionAuthority = new FunctionAuthority();
			functionAuthority.setRole(rolePo);
			functionAuthority.setMenu(menuTreeDao.load(it.next()));
			functionAuthorities.add(functionAuthority);
		}
		rolePo.setFunctionAuthorize(functionAuthorities);
		//3 设置角色的所属组织机构
		String organizeId = roleVo.getOrganizationId();
		if (StringUtils.isNotEmpty(organizeId)) {
			rolePo.setOrganization(organizeDao.load(organizeId));
		} else {
			rolePo.setOrganization(null);
		}
		model.addInfo("save.success");
		return model;
	}

	@Override
	public RoleModel list(RoleModel model) {
		String currentUserOrganizeId = model.getUser().getOrganizationId();
		String currentUserOrganizePath = organizeDao.getOrganizePath(currentUserOrganizeId);
		roleDao.findPageByExample(model.getPage(), model.getRole(), currentUserOrganizePath);
		return model;
	}

	/**
	 * 新增角色或修改角色时操作 新增: 角色编号和名称不能重复,同进保存相应角色和页签关联表中
	 *
	 * @param model
	 * @return model
	 */
	@Override
	public RoleModel addRole(RoleModel model) {
		Assert.notNull(model.getRoleAuth(), "菜单权限不能为空");
		Role roleVo = model.getRole();
		Role rolePo = new Role();
		//复制属性
		mapper.map(roleVo, rolePo);
		//增加功能权限
		String[] menus = model.getRoleAuth().split(",");
		Set<String> auths = new HashSet<String>();
		List<FunctionAuthority> functionAuthorities = new ArrayList<FunctionAuthority>();
		//去掉重复的菜单ID
		for (String menu : menus) {
			if (StringUtils.isNotEmpty(menu))
				auths.add(menu);
		}
		for (Iterator<String> it = auths.iterator(); it.hasNext(); ) {
			FunctionAuthority functionAuthority = new FunctionAuthority();
			functionAuthority.setRole(rolePo);
			functionAuthority.setMenu(menuTreeDao.load(it.next()));
			functionAuthorities.add(functionAuthority);
		}
		rolePo.setFunctionAuthorize(functionAuthorities);
		//设置角色的所属组织机构
		String organizeId = roleVo.getOrganizationId();
		if (StringUtils.isNotEmpty(organizeId)) {
			rolePo.setOrganization(organizeDao.load(organizeId));
		}
		roleDao.save(rolePo);
		model.addInfo("save.success");
		return model;
	}

	@Override
	public RoleModel loadRole(RoleModel model) {
		if (StringHelper.isNotEmpty(model.getRole().getId())) {
			model.setRole(roleDao.load(model.getRole().getId()));
			Set<String> set = roleDao.loadAuthorizedMenu(model.getRole().getId());
			if (set != null) {
				StringBuilder sb = new StringBuilder();
				for (String s : set) {
					sb.append(",\"");
					sb.append(s);
					sb.append("\"");
				}
				if (sb.length() > 0)
					sb.deleteCharAt(0);
				model.setRoleAuth(sb.toString());
			}
		}
		return model;
	}

	/**
	 * 删除判断角色下有没有用户(有相关用户不能删除)
	 * 删除时删除角色相关权限表
	 *
	 * @param model
	 * @return model
	 */
	@Override
	public RoleModel deleteRole(RoleModel model) {
		Role rolePo = roleDao.load(model.getRole().getId());
		if (rolePo.getUsers() != null && rolePo.getUsers().size() > 0) {
			model.addError("该角色已经有用户，不能删除");
			return model;
		}
		roleDao.delete(rolePo);
		model.addInfo("delete.success");
		return model;
	}

	/**
	 * 加载当前用户的可分配资源
	 * 可分配的组织机构
	 *
	 * @param model
	 * @return
	 */
	@Override
	public RoleModel loadAvailableResource(RoleModel model) {
		String organizeId = model.getUser().getOrganizationId();
		model.setOrganization(organizeDao.getSubOrganization(organizeId));
		return model;
	}
}
